<template>
  <!-- 卡业务明细-圈存明细表 -->
  <div class="revusuion">
    <el-table
      v-loading="loading"
      :data="detailslist"
      ref="table"
      border
      highlight-current-row
      style="width: 100%"
      :header-cell-style="headFirst"
      :cell-style="
        detailsTotal ? (res) => headFirst_col(res, detailslist) : () => {}
      "
    >
      <el-table-column
        prop="cardNumber"
        label="卡号"
        v-if="formThead8.cardNumber.checked"
        min-width="110px"
      ></el-table-column>
      <el-table-column prop="userName" label="姓名" v-if="formThead8.userName.checked"></el-table-column>
      <el-table-column
        prop="userNumber"
        label="人员编号"
        v-if="formThead8.userNumber.checked"
        min-width="110px"
      ></el-table-column>
      <el-table-column
        prop="departmentName"
        label="部门"
        v-if="formThead8.departmentName.checked"
        min-width="120px"
      ></el-table-column>
      <el-table-column
        prop="walletName"
        label="钱包名称"
        v-if="formThead8.walletName.checked"
        min-width="120px"
      ></el-table-column>
      <el-table-column
        prop="expenditure"
        label="操作金额(元)"
        v-if="formThead8.expenditure.checked"
        min-width="100px"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.expenditure | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="originBalance" label="原卡余额(元)" v-if="formThead8.originBalance.checked">
        <template slot-scope="scope">
          <div>{{ scope.row.originBalance | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="newBalance" label="现卡余额(元)" v-if="formThead8.newBalance.checked">
        <template slot-scope="scope">
          <div>{{ scope.row.newBalance | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="dataMakeTime"
        label="操作时间"
        v-if="formThead8.dataMakeTime.checked"
        min-width="148px"
      ></el-table-column>
      <!-- <el-table-column
        prop="isSuccess"
        label="交易状态"
        v-if="formThead8.isSuccess.checked"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.isSuccess | isSuccesstype }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="cardState"
        label="卡状态"
        v-if="formThead8.cardState.checked"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.cardState | filetercardState }}</div>
        </template>
      </el-table-column>-->
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChangepage"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="recordCount"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import bus from '@/bus.js'
export default {
  data() {
    return {
      loading: false,
      detailsTotal: null,
      detailslist: [],
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},
      formThead8: {
        cardNumber: { label: '卡号', prop: 'cardNumber', checked: true },
        userName: { label: '姓名', prop: 'userName', checked: true },
        userNumber: { label: '人员编号', prop: 'userNumber', checked: true },
        departmentName: {
          label: '部门',
          prop: 'departmentName',
          checked: true
        },
        walletName: { label: '钱包名称', prop: 'walletName', checked: true },
        expenditure: {
          label: '操作金额(元)',
          prop: 'expenditure',
          checked: true
        },
        newBalance: {
          label: '现卡余额(元)',
          prop: 'newBalance',
          checked: true
        },
        originBalance: {
          label: '原卡余额(元)',
          prop: 'originBalance',
          checked: true
        },
        dataMakeTime: {
          label: '操作时间',
          prop: 'dataMakeTime',
          checked: true
        }
        // isSuccess: { label: '交易状态', prop: 'isSuccess', checked: true },
      },
      detailslistExportlist: [],
      filename: '圈存明细表'
    }
  },
  mounted() {
    bus.$on('listenToA8', this.getHeaderDate)
  },
  props: [
    'userName',
    'departmentGuid',
    'datetime',
    'unitGuid',
    'waterWalletNo'
  ],
  filters: {
    filetercardState: function(cardState) {
      if (cardState == 0) {
        return (cardState = '可用')
      } else if (cardState == 1) {
        return (cardState = '不可用')
      }
    }
  },
  methods: {
    getHeaderDate(val) {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
      this.formThead8 = val
    },

    async getrechargedetailinit() {
      this.pageNum = 1
      this.searchInfo = {}
      if (this.userName !== null && this.userName !== '') {
        this.searchInfo.userName = this.userName
      }
      if (this.departmentGuid !== null && this.departmentGuid !== '') {
        this.searchInfo.departmentGuid = this.departmentGuid
      }
      if (this.datetime !== null && this.datetime !== '') {
        this.searchInfo.startTime = this.datetime[0]
        this.searchInfo.endTime = this.datetime[1]
      }
      this.searchInfo.unitGuid = this.unitGuid
      this.searchInfo.walletNo = this.waterWalletNo
      this.detailsTotal = null
      this.detailsTotal = await this.getTotal()
      this.getconsumptionrevisionlist()
    },
    // 获取圈存报表合计数据
    getTotal() {
      let _this = this
      _this.loading = true
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl('/card/report/consume-load-total'),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: _this.searchInfo,
              messageType: 0
            })
          })
          .then(({ data }) => {
            _this.loading = false
            if (data.messageCode == 200) {
              resolve(data.messageContent)
            } else {
              reject(data.errorMessage)
              this.$message.error(data.errorMessage)
            }
          })
      })
    },
    // 获取圈存报表数据
    getconsumptionrevisionlist() {
      this.loading = true
      this.$http({
        url: this.$http.adornUrl('/card/report/consume-load'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        if (data.messageCode == 200) {
          // data.messageContent.data = [
          //   {
          //     unitGuid: "4350df8e-c5a5-454e-9537-0877430dbffd",
          //     departmentGuid: "2486f0b3-50dc-44a0-898d-906fe4745b4a",
          //     departmentName: "1905班",
          //     isSuccess: 1,
          //     userName: "于兆祥",
          //     userGuid: "10b16c12-2888-431b-b033-418387b9add6",
          //     userNumber: "19050040",
          //     cardNumber: "1406434826",
          //     originBalance: 0,
          //     expenditure: -1500,
          //     newBalance: 188400,
          //     dataMakeTime: "2020-09-13 10:20:03",
          //     "cardState":1
          //   },
          // ];
          this.detailslist = data.messageContent.data
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
          if (data.messageContent.data.length == 0) {
            this.$message({
              message: '查询成功当前暂无数据',
              type: 'success'
            })
          }
          if (data.messageContent.data.length != 0) {
            this.detailslist.push({
              ...this.detailsTotal,
              cardNumber: '合计:',
              departmentName: ''
            })
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 打印或导出操作
    async exportlist(type) {
      if (this.detailslist.length == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
      }
      await this.outexecel()
      if (type == 'print') {
        this.printJS()
      } else {
        this.export2Excel()
      }
    },
    // 拿到表头数据
    getIsPrint() {
      // s
      let valArr = []
      let tHeader = []
      Object.keys(this.formThead8).map(item => {
        if (this.formThead8[item].checked) {
          valArr.push(this.formThead8[item].prop)
          tHeader.push(this.formThead8[item].label)
        }
      })
      return { filterValArr: valArr, tHeader }
    },
    // 打印
    printJS() {
      let someJSONdata = this.detailslistExportlist
      const title = '圈存明细表'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据,filterValArr为数据值，tHeader为数据标题，一一对应
      const { filterValArr, tHeader } = this.getIsPrint()
      filterValArr.map((item, index) => {
        if (filterValArr[index] == 'dataMakeTime') {
          properties.push({
            displayName: tHeader[index],
            field: filterValArr[index],
            columnSize: 130 / (Object.keys(this.formThead8).length + 1) + '%'
          })
        } else {
          properties.push({
            displayName: tHeader[index],
            field: filterValArr[index],
            columnSize: 100 / (Object.keys(this.formThead8).length + 1) + '%'
          })
        }
      })
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            'yyyy-MM-dd'
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            'yyyy-MM-dd'
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    // 获取打印和导出数据
    outexecel() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl('/card/report/consume-load'),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo
              },
              messageType: _this.messageType
            })
          })
          .then(({ data }) => {
            if (data.messageCode === 200) {
              // data.messageContent.data = [
              //   {
              //     unitGuid: "4350df8e-c5a5-454e-9537-0877430dbffd",
              //     departmentGuid: "2486f0b3-50dc-44a0-898d-906fe4745b4a",
              //     departmentName: "1905班",
              //     isSuccess: 1,
              //     userName: "于兆祥",
              //     userGuid: "10b16c12-2888-431b-b033-418387b9add6",
              //     userNumber: "19050040",
              //     cardNumber: "1406434826",
              //     originBalance: 0,
              //     expenditure: -1500,
              //     newBalance: 188400,
              //     dataMakeTime: "2020-09-13 10:20:03",
              //     "cardState":1
              //   },
              // ];
              _this.detailslistExportlist = data.messageContent.data
              if (data.messageContent.data.length != 0) {
                _this.detailslistExportlist.push({ ..._this.detailsTotal })
              }
              for (var i = 0; i < _this.detailslistExportlist.length; i++) {
                _this.detailslistExportlist[i].expenditure = _this.amountyua(
                  _this.detailslistExportlist[i].expenditure
                )
                _this.detailslistExportlist[i].newBalance = _this.amountyua(
                  _this.detailslistExportlist[i].newBalance
                )
                _this.detailslistExportlist[i].originBalance = _this.amountyua(
                  _this.detailslistExportlist[i].originBalance
                )
                // 拿到isSuccesstype过滤器对isSuccess进行过滤
                _this.detailslistExportlist[
                  i
                ].isSuccess = _this.$options.filters.isSuccesstype(
                  _this.detailslistExportlist[i].isSuccess
                )
                // 拿到filetercardState过滤器对cardState进行过滤
                _this.detailslistExportlist[
                  i
                ].cardState = _this.$options.filters.filetercardState(
                  _this.detailslistExportlist[i].cardState
                )
              }
              resolve(_this.detailslistExportlist)
            } else {
              reject(data.errorMessage)
              _this.$message.error(data.errorMessage)
            }
          })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    export2Excel() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel')
        const multiHeader = []
        const multiHeader2 = []
        const merges = []
        let tHeaderarr = []
        const { tHeader, filterValArr } = this.getIsPrint()
        const filterVal = filterValArr
        const list = this.detailslistExportlist
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime
        })
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.getconsumptionrevisionlist()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.getconsumptionrevisionlist()
    }
  }
}
</script>

<style lang="scss" scoped>
.revusuion {
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }
}
.page {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>